'use client';
import React, { useState } from 'react';
import { useForm } from 'react-hook-form';
import { Button, TextField, Container, Box, Typography } from '@mui/material';
import { PDFDocument, rgb } from 'pdf-lib';
import fontkit from '@pdf-lib/fontkit';
import { saveAs } from 'file-saver';

const ResumeForm = () => {
    const { register, handleSubmit } = useForm();
    const [photo, setPhoto] = useState<File | null>(null);

    const onSubmit = async (data: any) => {
        const pdfDoc = await PDFDocument.create();
        pdfDoc.registerFontkit(fontkit);

        // 加载中文字体
        const fontBytes = await fetch('http://localhost:3000/simsun.ttf').then(res => res.arrayBuffer());
        const customFont = await pdfDoc.embedFont(fontBytes);

        const page = pdfDoc.addPage([600, 800]);
        const { width, height } = page.getSize();

        page.drawText('我的简历', {
            x: 50,
            y: height - 50,
            size: 25,
            font: customFont,
            color: rgb(0, 0, 0),
        });

        const startY = height - 100;
        const lineHeight = 30;

        page.drawText(`姓名: ${data.name}`, {
            x: 50,
            y: startY,
            size: 20,
            font: customFont,
            color: rgb(0, 0, 0),
        });

        page.drawText(`邮箱: ${data.email}`, {
            x: 50,
            y: startY - lineHeight,
            size: 20,
            font: customFont,
            color: rgb(0, 0, 0),
        });

        page.drawText(`电话: ${data.phone}`, {
            x: 50,
            y: startY - 2 * lineHeight,
            size: 20,
            font: customFont,
            color: rgb(0, 0, 0),
        });

        page.drawText(`地址: ${data.address}`, {
            x: 50,
            y: startY - 3 * lineHeight,
            size: 20,
            font: customFont,
            color: rgb(0, 0, 0),
        });

        page.drawText(`教育背景: ${data.education}`, {
            x: 50,
            y: startY - 4 * lineHeight,
            size: 20,
            font: customFont,
            color: rgb(0, 0, 0),
        });

        page.drawText(`工作经验: ${data.experience}`, {
            x: 50,
            y: startY - 5 * lineHeight,
            size: 20,
            font: customFont,
            color: rgb(0, 0, 0),
        });

        if (photo) {
            const imageBytes = await photo.arrayBuffer();
            let image;
            if (photo.type === 'image/jpeg' || photo.type === 'image/jpg') {
                image = await pdfDoc.embedJpg(imageBytes);
            } else if (photo.type === 'image/png') {
                image = await pdfDoc.embedPng(imageBytes);
            } else {
                console.error('Unsupported image format');
                return;
            }

            const imgWidth = 150;
            const imgHeight = (image.height / image.width) * imgWidth;

            page.drawImage(image, {
                x: width - imgWidth - 50,
                y: height - imgHeight - 50,
                width: imgWidth,
                height: imgHeight,
            });
        }

        const pdfBytes = await pdfDoc.save();
        saveAs(new Blob([pdfBytes], { type: 'application/pdf' }), 'resume.pdf');
    };

    const handlePhotoChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        const file = event.target.files?.[0];
        if (file) {
            setPhoto(file);
        }
    };

    return (
        <Container>
            <Box
                sx={{
                    padding: 4,
                    border: '1px solid #ccc',
                    borderRadius: 2,
                    marginBottom: 2,
                }}
            >
                <Typography variant="h4" gutterBottom>
                    我的简历
                </Typography>
                <form onSubmit={handleSubmit(onSubmit)}>
                    <TextField
                        label="姓名"
                        fullWidth
                        margin="normal"
                        {...register('name')}
                    />
                    <TextField
                        label="邮箱"
                        fullWidth
                        margin="normal"
                        {...register('email')}
                    />
                    <TextField
                        label="电话"
                        fullWidth
                        margin="normal"
                        {...register('phone')}
                    />
                    <TextField
                        label="地址"
                        fullWidth
                        margin="normal"
                        {...register('address')}
                    />
                    <TextField
                        label="教育背景"
                        fullWidth
                        margin="normal"
                        multiline
                        rows={4}
                        {...register('education')}
                    />
                    <TextField
                        label="工作经验"
                        fullWidth
                        margin="normal"
                        multiline
                        rows={4}
                        {...register('experience')}
                    />
                    <input
                        type="file"
                        accept="image/*"
                        onChange={handlePhotoChange}
                        style={{ marginTop: 16 }}
                    />
                    <Button type="submit" variant="contained" color="primary" sx={{ mt: 2 }}>
                        下载 PDF
                    </Button>
                </form>
            </Box>
        </Container>
    );
};

export default ResumeForm;
